<?php

namespace app\controller\admin\module\user;

use app\controller\admin\module\AdminBaseController;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * @auth-name 玩家列表
 * @auth-alias user
 */
class Index extends AdminBaseController
{
    protected string $modelName = 'user';
    /**
     * 主页
     * @auth-name 主页
     * @auth-alias index
     * @return View
     */
    public function index(): View
    {
        return fetch('/admin/user/index');
    }

    /**
     * @auth-name 列表
     * @auth-alias list
     * @return Json
     */
    public function list(): Json
    {
        $limit = values('limit', 10);
        $this->model->customLeft = [
            'table' => 'userCompilation',
            'on' => 'userCompilation.uid = '.$this->modelName.'.id'
        ];
        $condition = [];
        $this->condition($condition);
        $list = $this->model->getPageList($condition, $this->modelName.'.id, username, login_num, last_login_time, createtime, ' . $this->model->customLeft['table'] . '.score', $this->modelName.'.createtime desc', ['start' => ((values('page', 10) - 1) * $limit), 'limit' => $limit]);
        return json($list);
    }

    private function condition(&$condition = []){
        $uidKeywordField = values('uid_keyword_field');
        $uidKeywordValue = values('uid_keyword_value');
        if(!empty($uidKeywordField) and !empty($uidKeywordValue)){
            if($uidKeywordField == 'username'){
                $condition[] = [$uidKeywordField, 'like' , $uidKeywordValue. '%'];
            }else{
                $condition[$this->modelName . '.' .$uidKeywordField] = $uidKeywordValue;
            }
        }
    }

    /**
     * 修改密码
     * @auth-name 修改密码
     * @auth-alias cpwd
     * @auth-request-method post
     * @return Json
     */
    public function changePassword(): Json
    {
        $uid = values('uid');
        empty($uid) and errorData();
        $password = values('password');
        $repassword = values('repassword');
        try {
            $this->validate([
                'password' => $password,
                'repassword' => $repassword,
            ],[
                'password|密码' => ['require'],
                'repassword|确认密码' => ['require', 'confirm:password'],
            ], ['repassword.confirm' => '两次密码不一致']);
            if($this->model->edit(['id' => $uid], ['pwd' => password_hash($password, PASSWORD_BCRYPT, ['cost' => 12])])){
                putAdminLog("更改玩家密码");
                return responseMsg('更改成功', 200);
            }
            return responseMsg('更改失败');
        }catch (ValidateException $e){
            return responseMsg($e->getError());
        }
    }

    /**
     * 编辑
     * @auth-name 编辑
     * @return void
     */
    public function edit(){

    }
}